const state = {
  cartProducts: []
}
const getters = {
  totalCount (state) {
    return state.cartProducts.reduce((count, prod) => {
      return count + prod.count
    }, 0)
  },
  totolPrice (state) {
    return state.cartProducts.reduce((price, prod) => {
      return price + prod.totalPirce
    }, 0).toFixed(2)
  },
  checkedTotalCount(state) {
    return state.cartProducts.reduce((count, prod) => {
      return count + (prod.isChecked ? prod.count : 0)
    }, 0)
  },
  chenckedTotolPrice(state) {
    console.log(state)
    return state.cartProducts.reduce((price, prod) => {
      if(prod.isChecked) {
        return price + prod.totalPirce
      }
      return price
    }, 0)
  }
}
const mutations = {
  addToCart(state, product) {
    // 判断该商品是否已经存在 cartProducts 中
    const prod = state.cartProducts.find(item => item.id === product.id)
    if(prod) {
      prod.count++,
      prod.totalPirce += product.price
      prod.isChecked = true
    } else {
      state.cartProducts.push({
        // {id, title, price}
        ...product,
        count: 1,
        totalPirce: product.price,
        isChecked: true
      })
    }
  },
  deleteFromCart(state, prodId) {
    const index = state.cartProducts.find(item => {item.id === prodId})
    index !== -1 && state.cartProducts.splice(index,  1)
  },
  updateProductChecked(state, {
    prodId, checked
  }) {
    const prod = state.cartProducts.find(prod => prod.id === prodId)
    prod && (prod.isChecked = checked)
  },
  updateAllProductsChecked(state, checked) {
    state.cartProducts.forEach(prod => {
      prod.isChecked = checked
    })
  },
  updateProductCount(state, {
    prodId, count
  }) {
    const prod = state.cartProducts.find(item => item.id === prodId)
    if(prod) {
      prod.count = count 
      prod.totalPirce = count * prod.price
    }
  }
}
const actions = {}

export default {
  namespaced : true,
  state,
  getters,
  mutations,
  actions
}